local MathUtils = {}

-- /*
-- * 计算相对原点坐标系两点间的夹角
-- * @param start：开始点
-- * @param target：目标点
-- */
function MathUtils.calcAngle(start, target)
    if start.x == target.x then
        if start.y < target.y then
            return 0
        else
            return CS.UnityEngine.Mathf.PI
        end
    end

    if start.y == target.y then
        if start.x < target.x then
            return CS.UnityEngine.Mathf.PI
        else
            return CS.UnityEngine.Mathf.PI * 1.5
        end
    end
    local dx = target.x - start.x
    local dy = target.y - start.y
    local angle = CS.UnityEngine.Mathf.Atan(CS.UnityEngine.Mathf.Abs(dx / dy))
    if start.x < target.x and start.y < target.y then
        return angle
    elseif start.x < target.x and start.y > target.y then
        return CS.UnityEngine.Mathf.PI - angle
    elseif start.x > target.x and start.y > target.y then
        return CS.UnityEngine.Mathf.PI + angle
    else
        return 2 * CS.UnityEngine.Mathf.PI - angle
    end
end

-- /*
-- * 通过源方向获取朝摄像机前方的方向向量
-- * @param src：源方向
-- * @param cameraForward : 摄像机方向
-- * @return 旋转后的方向
function MathUtils.RotateByCameraForward(src, cameraForward)
    local src2 = CS.UnityEngine.Vector2(src.x, src.z)
    local dir = CS.UnityEngine.Vector2(cameraForward.x, cameraForward.z)
    dir = dir.normalized
    local angle = MathUtils.calcAngle(CS.UnityEngine.Vector2(0, 0), dir)
    angle = CS.UnityEngine.Mathf.PI * 2 - angle
    local m11, m12, m21, m22
    m11 = CS.UnityEngine.Mathf.Cos(angle)
    m12 = CS.UnityEngine.Mathf.Sin(angle)
    m21 = -CS.UnityEngine.Mathf.Sin(angle)
    m22 = CS.UnityEngine.Mathf.Cos(angle)
    local result = CS.UnityEngine.Vector2(0, 0)
    result.x = src2.x * m11 + src2.y * m21
    result.y = src2.x * m12 + src2.y * m22
    return CS.UnityEngine.Vector3(result.x, 0, result.y)
end

function MathUtils.clamp(value, min, max)
    return CS.UnityEngine.Mathf.Clamp(value, min, max)
end

return MathUtils
